package com.xy.util;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Random;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


import com.xy.math.Vector2f;

public class Utils {
	private static Logger log = LoggerFactory.getLogger(Utils.class);
	
	// 引导类型 ：强制引导
	public static int GUIDE_TYPE_FORCE = 0;

	// 新的gameObject类型
	public static final int TYPE_MONSTERGROUP = 11;// 怪物组
	public static final int TYPE_PASSDOOR = 12;// 阻挡门
	public static final int TYPE_REWARD = 13;// 掉落拾取对象
	public static final int TYPE_BREAKABLE = 9;// 可破坏
	public static final int TYPE_MAPISLAND = 14;// 地图中的浮岛
	public static final int TYPE_MAPSWITCH = 15;// 地图中的开关
	public static final int TYPE_CUSTOMSAFEAREA = 18;// 地图中的非安全区
	public static final int TYPE_GUIDEPOINT = 19;// 地图中的指引精灵
	public static final int TYPE_SCALECONTROLLER = 118;// 缩放点
	public static final int TYPE_SOUND_EFFECT = 119;// 场景音效点
	public static final int TYPE_TREASURE_BOX = 20;// 藏宝箱
	public static final int TYPE_TIMER = 21;// 计时器
	public static final int TYPE_BUFFREFRESH = 22;// buff刷新点
	public static final int TYPE_MAPDOT = 24;// 地图点缀
	public static final int TYPE_TOTEM = 25;// 图腾
	public static final int TYPE_DROPGROUP = 26;// 地图掉落组
	public static final int TYPE_SHIMO_WARRIOR = 27;// 使魔战士
	public static final int TYPE_TRIGGER = 28;// 地图触发器对象

	public static Random RND = new Random();
	/**
	 * 默认的显示名称方式
	 */
	public static final byte SHOW_NAME_STYLE_NORMAL = 0;

	/**
	 * 不显示名称
	 */
	public static final byte SHOW_NAME_STYLE_NO_SHOW = 1;

	/**
	 * 显示名称
	 */
	public static final byte SHOW_NAME_STYLE_FORCE_SHOW = 2;

	// 创建默认属性数值
	public static final int DELETE_INT = 1;
	public static final byte DELETE_BYTE = 1;
	public static final short DELETE_SHORT = 1;
	public static final String DELETE_STRING = " ";

	public static File file = null;
	public static FileOutputStream fos = null;
	public static PrintWriter out = null;

	static {

		// file = new File("D:/serverLog.txt");
		// try {
		// if(!file.exists()){
		// file.createNewFile();
		// }
		// fos = new FileOutputStream(file);
		// out = new PrintWriter(new BufferedWriter(new
		// OutputStreamWriter(fos,"utf-8")));
		// } catch (Exception e) {
		// e.printStackTrace();
		// }
	}

	public static void logToFile(String str) {
		try {
			// out.write(Time.currTime + " " + str + "\r\n");
			// out.flush();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * @param a
	 * @param b
	 * @return a为高32位, b为低32位
	 */
	public static long intToLong(int a, int b) {
		long redoLong = 0;
		long a1 = ((long) a << 32) & 0xFFFFFFFF00000000L;
		long b1 = b & 0x00000000FFFFFFFFL;
		redoLong = a1 | b1;
		return redoLong;
	}

	// byte数组转成long
	public static long byteToLong(byte[] b) {
		long s = 0;
		long s0 = b[0] & 0xff;// 最低位
		long s1 = b[1] & 0xff;
		long s2 = b[2] & 0xff;
		long s3 = b[3] & 0xff;
		long s4 = b[4] & 0xff;// 最低位
		long s5 = b[5] & 0xff;
		long s6 = b[6] & 0xff;
		long s7 = b[7] & 0xff;

		// s0不变
		s1 <<= 8;
		s2 <<= 16;
		s3 <<= 24;
		s4 <<= 8 * 4;
		s5 <<= 8 * 5;
		s6 <<= 8 * 6;
		s7 <<= 8 * 7;
		s = s0 | s1 | s2 | s3 | s4 | s5 | s6 | s7;
		return s;
	}
	
	/**
     * Java 执行Linux Shell 脚本

     */
    public static void execLinuxShell (String file, String... params) {
    	try {
    		
    		StringBuffer sb = new StringBuffer();
    		if (params != null && params.length > 0) {
    			for (String param : params) {
        			sb.append(param).append(" ");
        		}	
    		}
    		
    		//授权脚本
	    	String cmdString = "chmod 777 " + file;
	    	Process process;
			process = Runtime.getRuntime().exec(cmdString);
			process.waitFor();//线程阻塞，一直等到命令执行完成
			
			log.info("==========>授权完成");
			
			//执行脚本
			cmdString = "sh " + file;
			if (sb.toString().trim().length() > 0) {
				cmdString = "sh " + file + " " + sb.toString().trim();
			}
			log.info("====执行脚本======>" + cmdString);
			process = Runtime.getRuntime().exec(cmdString);
			
			String string = "";
			BufferedReader inputReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
			BufferedReader errorReader = new BufferedReader(new InputStreamReader(process.getErrorStream()));
			log.info("input info--------->");
			while ((string = inputReader.readLine()) != null) {
				log.info(string);
			}
			inputReader.close();
			log.info("error info--------->");
			while ((string = errorReader.readLine()) != null) {
				log.info(string);
			}
			errorReader.close();
			
			log.info("==========>启动完成");
			
			process.waitFor();
		} catch (Exception e) {
			e.printStackTrace();
		}
    }

	/**
	 * @param bytes
	 * @return将字节转换为输入流 （便于宠物的读取）
	 */
	public static DataInputStream getDataInputStreamFromBytes(byte[] bytes) {
		ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
		DataInputStream dis = new DataInputStream(bais);
		return dis;
	}

	// n从零开始检测第n位为1
	public static boolean checkIntN(int b, int n) {
		if (n > 31 || n < 0) {
			return false;
		}
		return ((b & (1 << n)) == (1 << n));
	}

	// n从零开始设置第n位为1
	public static int setIntN(int b, int n) throws Exception {
		if (n > 31 || n < 0)
			throw new Exception();
		int t = b | (1 << n);
		return t;

	}

	/**
	 * n从零开始设置第n位为0
	 * 
	 * @param b
	 * @param n
	 * @return
	 * @throws Exception
	 */
	public static int setIntNotN(int b, int n) throws Exception {
		if (n > 31 || n < 0)
			throw new Exception();
		int t = b & (~(1 << n));
		return t;

	}

	public static boolean inDistance(int srcX, int srcY, int destX, int destY, int distance) {
		int xdist = Math.abs(destX - srcX);
		int ydist = Math.abs(destY - srcY);
		return xdist * xdist + ydist * ydist <= distance * distance;
	}

	public static int calcAngle(int x, int y, int x1, int y1) {
		int angle = (int) Math.round(Math.toDegrees((float) Math.atan2(y - y1, x1 - x)));
		if (angle < 0)
			return (360 + angle);
		return angle;
	}

	public static int getDistance(int srcX, int srcY, int destX, int destY) {
		int xdist = Math.abs(destX - srcX);
		int ydist = Math.abs(destY - srcY);
		return xdist * xdist + ydist * ydist;
	}

	/**
	 * 根据产出最小量和最大量随机产生产出数量
	 */
	public static int getRandomAmount(int minAmount, int maxAmount) {
		if (maxAmount > minAmount) {
			int randomNum = RND.nextInt((maxAmount - minAmount) + 1);
			return (randomNum + minAmount);
		} else if (maxAmount == minAmount) {
			return minAmount;
		}
		return 0;
	}

	/**
	 * 得到随机值
	 * 
	 * @param <T>
	 * @param list
	 * @return
	 */
	public static <T> T getRandomObject(List<T> list) {
		T result = null;
		if (list != null && list.size() > 0) {
			int index = RND.nextInt(list.size());
			result = list.get(index);
		}
		return result;
	}

	/**
	 * 得到随机值
	 * 
	 * @param <T>
	 * @param list
	 * @return
	 */
	public static <T> List<T> getRandomObject(List<T> list, int count) {
		List<T> result = null;
		if (list != null && list.size() > count) {
			result = new ArrayList<T>();
			List<T> temp = new LinkedList<T>(list);
			for (int i = 0; i < count; i++) {
				int index = RND.nextInt(temp.size());
				T t = temp.remove(index);
				result.add(t);
			}
		} else {
			result = list;
		}
		return result;
	}

	/**
	 * 判断地图是否副本
	 */
	// public static boolean isInstanceMap(int mapId) throws VMapException{
	// //VMap map =
	// ServiceContainer.getDefault().get(NormalVMapManager.class).getMap(mapId);
	// //if(null == map){
	// // throw new VMapException("目标场景不存在！");
	// //}
	// //GameMapDefinition def = map.getDef();
	// //return def.mapInfo.isCopy;
	// VMapManager manager = Platform.getWorld().getVMapManager(mapId);
	// if(null == manager){
	// throw new VMapException("目标场景不存在！");
	// }
	// return (manager instanceof NormalInstanceVMapManager || manager instanceof
	// TongInstanceVMapManager || manager instanceof TongBattleInstanceVMapManager);
	// }
	/**
	 * 是否是副本
	 * 
	 * @param mapId
	 * @return
	 * @throws VMapException
	 */

	// public static boolean isInstanceMap0(int mapId) throws VMapException{
	// VMapManager manager = Platform.getWorld().getVMapManager(mapId);
	// if(null == manager){
	// throw new VMapException("目标场景不存在！");
	// }
	// return (manager instanceof NormalInstanceVMapManager);
	// }
	/**
	 * 是否是战场
	 * 

	 */


	public static void main(String[] args) {
		List<Integer> srcList = new ArrayList<Integer>();
		for (int i = 0; i < 4; i++) {
			srcList.add(i);
		}
		List<Integer> list = getRandomObject(srcList, 3);
		System.out.print(list);
	}

	/**
	 * 根据概率数组得到随机下标
	 * 
	 * @param rateArray
	 * @return
	 */
	public static int getRandomIndex(int[] rateArray) {
		int ret = -1;
		int total = 0;
		for (int arr : rateArray) {
			total += arr;
		}
		ret = getRandomIndex(rateArray, total);
		return ret;
	}

	public static int getRandomIndex(int[] rateArray, int total) {
		int ret = -1;
		int rand = getRandomAmount(0, total - 1);
		total = 0;
		for (int i = 0; i < rateArray.length; i++) {
			total += rateArray[i];
			if (rand < total) {
				ret = i;
				break;
			}
		}
		return ret;
	}
	
	public static int[] quickSort(int[] arr, int low, int high) {
		//为后面的递归使用
		int lowStart = low;
		int highEnd = high;
		if (low < high) {
			int pivokey = arr[low];
			while (low < high) {
				//如果都是大于pivokey，high指针往前移
				while (low < high && arr[high] > pivokey) {
					high--;
				}
				//这里low++是先把arr[low]赋值为arr[high]，再low+=1，因为这个值是比pivokey小的，下一次不用比较了
				if (low < high)
				arr[low++] = arr[high];
				//如果都是小于pivokey，low指针往后移
				while (low < high && arr[low] < pivokey) {
					low++;
				}
				//这里的high--和上面同理
				if (low < high)
				arr[high--] = arr[low];
			}
			arr[low] = pivokey;
			quickSort(arr, lowStart, low - 1);
			quickSort(arr, low + 1, highEnd);
		}
		return arr;
	}
	
	/**
	 * 获得中间重复利用的id
	 */
	public static int getRecycleId(int[] ss) {
		//排序
		int count = ss.length;
		Utils.quickSort(ss, 0, ss.length - 1);
		int lastId = 0;
		for (int i=0; i < count; i++) {
			if (ss[i] - lastId > 1) {
				//不连续了
				return lastId+1;
			}
			lastId = i + 1;
		}
		//原有的都是连续的
		return count + 1;
	}
	
	// /**
	// * 对array随机排序
	// * @param array
	// */
	// public static void randomSortArray(int[] array){
	// for(int i = 0; i < array.length - 1; i++){
	// int index = Utils.getRandomAmount(0, array.length - 1 - i);
	// int temp = array[index];
	// array[index] = array[array.length - 1 - i];
	// array[array.length - 1 - i] = temp;
	// }
	// }
	//
	// public static boolean inBlockRegion(Player player){
	// VMap map = player.getVMap();
	// GameMapDefinition def = map.getDef();
	//// if(def.mapInfo.allowPVP){
	//// return false;
	//// }
	// int x = player.getX();
	// int y = player.getY();
	// int h = def.map.tileInfo.length;
	// int w = def.map.tileInfo[0].length;
	// if ((x <= 0) || (y <= 0) || (y / 8) >= h || (x / 8) >= w) {
	// //出错的move信息太多，不打log了
	// //if ((x <= -50) || (y <= -50) || ((y / 8) - h >= 50)
	// // || ((x / 8) - w >= 50)) {
	// // Platform.getLog(LogEx.class).logCrack(p,
	// // "(MAP=" + map.getId() + ",X=" + x + ",Y=" + y + ")",
	// // "MOVE");
	// //}
	// return false;
	// }
	// byte[][] tileInfo = def.mapInfo.tileInfo;
	// if (tileInfo == null) {
	// tileInfo = def.map.tileInfo;
	// }
	// byte tmp = tileInfo[y / 8][x / 8];
	// if((tmp & (1 << 1)) == 0){
	// return true;
	// }else{
	// return false;
	// }
	// }
	/**
	 * 是否是pvp保护地图
	 * 
	 * @param map
	 * @return
	 */
	// public static boolean isPvpProtectedMap(VMap map){
	// boolean ret = false;
	// if(map != null && map.getDef().mapInfo instanceof GameMapInfoEx){
	// GameMapInfoEx gmie = (GameMapInfoEx)map.getDef().mapInfo;
	// ret = gmie.pvpProtected;
	// }
	// return ret;
	// }

	// public static boolean isInTongBattleInstance(int mapid) throws VMapException{
	// VMapManager manager = Platform.getWorld().getVMapManager(mapid);
	// if(null == manager){
	// throw new VMapException("目标场景不存在！");
	// }
	// return manager instanceof TongBattleInstanceVMapManager;
	// }
	/**
	 * 得到数组中出现次数最多的值
	 */
	public static int getMostValue(int[] array) {
		Map<Integer, Integer> countMap = new HashMap<Integer, Integer>();
		int maxTimes = 0;
		int maxMember = -1;
		if (array == null) {
			return 0;
		}
		for (Integer i : array) {
			if (countMap.containsKey(i)) {
				int value = countMap.get(i) + 1;
				countMap.put(i, value);
				if (value > maxTimes) {
					maxTimes = value;
					maxMember = i;
				}
			} else {
				countMap.put(i, 1);
			}
			if (maxTimes > array.length / 2)
				break;
		}
		return maxMember;
	}

	/**
	 * /** 获取时间指定的点和半径之内不在阻挡中的随机点
	 * 
	 * @param oraX
	 * @param oraY
	 * @param range
	 * @return
	 */
	// public static int[] getUnCollisonPoint(int oraX,int oraY,int
	// radius,VMapReference map,int maxTime){
	// int time = 0;
	// int[] ret = new int[2];
	// while(true){
	// time++;
	// ret = Utils.getPointRandom(oraX,oraY,radius);
	// try{
	// if(Utils.isInCollison(map,ret[0],ret[1]) && time < maxTime){
	// continue;
	// }
	// }catch(Exception e){
	// ret[0] = oraX;
	// ret[1] = oraY;
	//// e.printStackTrace();
	// }
	// if(time > maxTime){
	// ret[0] = oraX;
	// ret[1] = oraY;
	// break;
	// }
	// break;
	// }
	// return ret;
	// }
	/**
	 * 获取时间指定的点和半径之内的随机点

	 */
	public static int[] getPointRandom(int oraX, int oraY, int radius) {
		int[] ret = new int[2];
		ret[0] = RND.nextInt(radius >> 1) * (RND.nextInt(2) == 0 ? -1 : 1) + oraX;
		ret[1] = RND.nextInt(radius >> 1) * (RND.nextInt(2) == 0 ? -1 : 1) + oraY;
		return ret;
	}
	// public static boolean isInCollison(VMapReference map,int x,int y){
	//// int tileX = x / map.map.getDef().map.parent.getTileWidth();
	//// int tileY = y / map.map.getDef().map.parent.getTileHeight();
	// int tileX = x >> 3;
	// int tileY = y >> 3;
	// //如果为2表示这个点可以通过，如果为0表示不能通过
	// byte[][] testTileInfo = map.map.getDef().mapInfo.tileInfo;
	// if(tileY >= 0 && tileY < testTileInfo.length){
	// if(tileX >= 0 && tileX < testTileInfo[tileY].length){
	// if((testTileInfo[tileY][tileX] & 2) != 0){
	// return false;
	// }else{
	// return true;
	// }
	// }
	// }
	// return false;
	// }
	// 获取掉落组的通用奖励图标
	// public static List<Integer> getDropGroupIconIndex(List<SubDropGroup>
	// subGroup){
	// ProjectData projData = ProjectData.getActiveProject();
	// List<Integer> ret = new ArrayList<Integer>();
	// for(SubDropGroup group : subGroup){
	// for(DropItem item : group.dropGroup){
	// switch(item.dropType){
	// case DropItem.DROP_TYPE_ITEM:
	// ret.add(ShowAwardUtils.TYPE_ITEM);
	// break;
	// case DropItem.DROP_TYPE_EQUI:
	// ret.add(ShowAwardUtils.TYPE_EQU);
	// break;
	// case DropItem.DROP_TYPE_DROPGROUP:
	// DropGroupEx dropGroup = (DropGroupEx) projData.findObject(DropGroupEx.class,
	// item.dropID);
	// if(dropGroup != null){
	// ret.addAll(getDropGroupIconIndex(dropGroup.subGroup));
	// }
	// break;
	// case DropItem.DROP_TYPE_MONEY:
	// ret.add(ShowAwardUtils.TYPE_MONEY);
	// break;
	// case DropItem.DROP_TYPE_EXP:
	// ret.add(ShowAwardUtils.TYPE_EXP);
	// break;
	// case DropItemEx.DROP_TYPE_TREASURE:
	// ret.add(ShowAwardUtils.TYPE_TREASURE);
	// }
	// }
	// }
	// return ret;
	// }

	// public static int getIntValue(Element elem,String key,int defaultValue){
	// int ret = defaultValue;
	// String str = elem.getAttributeValue(key);
	// if(str == null || str == ""){
	// ret = defaultValue;
	// }else{
	// ret = Integer.parseInt(str);
	// }
	// return ret;
	// }
	// public static String getStringValue(Element elem,String key,String
	// defaultValue){
	// String ret = defaultValue;
	// String str = elem.getAttributeValue(key);
	// if(str == null){
	// ret = defaultValue;
	// } else {
	// ret = str;
	//
	// }
	// return ret;
	// }

	// public static boolean getBooleanValue(Element elem,String key,boolean
	// defaultValue){
	// boolean ret = defaultValue;
	// String str = elem.getAttributeValue(key);
	// if(str == null || str == ""){
	// ret = defaultValue;
	// }else{
	// ret = Boolean.parseBoolean(str);
	// }
	// return ret;
	// }

	/**
	 * 将掉落信息放入packet
	 * 
	 * @param packet
	 * @param gainList
	 */
	// public static void putGropAward(Packet packet, List<Gain> gainList){
	// List<InstanceAwardInfoObj> awardList = new ArrayList<InstanceAwardInfoObj>();
	// initAwardInfoList(gainList, awardList);
	// putInstanceAwardInfo(packet, awardList);
	// }

	/**
	 * 从掉落数据中获得奖励信息
	 * 
	 * @param gainList
	 * @param awardList
	 */
	// public static void initAwardInfoList(List<Gain> gainList,
	// List<InstanceAwardInfoObj> awardList) {
	// for (Gain gain : gainList) {
	// List<GainEntry> entrys = gain.getGainEntrys();
	// if (null == entrys)
	// continue;
	// for (int i = 0; i < entrys.size(); i++) {
	// GainEntry gainEntry = entrys.get(i);
	// if (null == gainEntry) {
	// continue;
	// }
	// InstanceAwardInfoObj award = getInstanceAwardInfoObj(gainEntry);
	// if (null != award) {
	// awardList.add(award);
	// break;
	// }else{
	// log.error("[INITAWARDINFO]CLASSNAME["+gainEntry.getClass().getSimpleName()+"]");
	// }
	// }
	// }
	// }

	/**
	 * 奖励列表
	 * 
	 * @param entrys
	 * @return
	 */
	// public static List<InstanceAwardInfoObj> getAwardInfoList(List<GainEntry>
	// entrys) {
	// List<InstanceAwardInfoObj> awardList = new ArrayList<InstanceAwardInfoObj>();
	// for (int i = 0; i < entrys.size(); i++) {
	// GainEntry gainEntry = entrys.get(i);
	// if (null == gainEntry) {
	// continue;
	// }
	// InstanceAwardInfoObj award = getInstanceAwardInfoObj(gainEntry);
	// if (null != award) {
	// awardList.add(award);
	// } else {
	// log.error("[INITAWARDINFO]CLASSNAME["
	// + gainEntry.getClass().getSimpleName() + "]");
	// }
	// }
	// return awardList;
	// }
	/**
	 * 将GainEntry的数据信息转成InstanceAwardInfoObj
	 * 
	 * @param gainEntry
	 * @return
	 */
	// public static InstanceAwardInfoObj getInstanceAwardInfoObj(
	// GainEntry gainEntry) {
	// InstanceAwardInfoObj award = null;
	// if (gainEntry instanceof ExpGainEntryRU) {
	// // 经验
	// ExpGainEntryRU exp = (ExpGainEntryRU) gainEntry;
	// award = new InstanceAwardInfoObj(DropItem.DROP_TYPE_EXP,
	// exp.getIconIndex(), exp.getShowName(), 0, exp.value, -1, -1);
	// } else if (gainEntry instanceof MoneyGainEntryRU) {
	// // 金钱
	// MoneyGainEntryRU money = (MoneyGainEntryRU) gainEntry;
	// award = new InstanceAwardInfoObj(DropItem.DROP_TYPE_MONEY,
	// money.getIconIndex(), money.getShowName(), 0, money.value, -1, -1);
	// } else if (gainEntry instanceof TreasureGainEntryRU) {
	// // 藏宝图
	// TreasureGainEntryRU treasure = (TreasureGainEntryRU) gainEntry;
	// award = new InstanceAwardInfoObj(
	// DropItemEx.DROP_TYPE_TREASURE,
	// treasure.getIconIndex(), treasure.getTitle(), 1,
	// treasure.value, -1, -1);
	// } else if (gainEntry instanceof FuWenTokenGainEntryRU) {
	// // 符文币
	// FuWenTokenGainEntryRU fuwen = (FuWenTokenGainEntryRU) gainEntry;
	// award = new InstanceAwardInfoObj(
	// DropItemEx.DROP_TYPE_FUWEN,
	// fuwen.getIconIndex(), fuwen.getTitle(), 0,
	// fuwen.value, -1, -1);
	// } else if (gainEntry instanceof BoundMoneyGainEntryRU) {
	// // 蓝钻
	// BoundMoneyGainEntryRU boundMoney = (BoundMoneyGainEntryRU) gainEntry;
	// award = new InstanceAwardInfoObj(
	// DropItemEx.DROP_TYPE_BMONEY,
	// boundMoney.getIconIndex(), boundMoney.getShowName(), 0,
	// boundMoney.value, -1, -1);
	// } else if (gainEntry instanceof GameItemGainEntry) {
	// // 物品或装备
	// GameItem item = ((GameItemGainEntry) gainEntry).getItem();
	// if (null != item) {
	// ItemTemplate template = item.getTemplate();
	// if (null != template) {
	// award = new InstanceAwardInfoObj(
	// DropItem.DROP_TYPE_ITEM,
	// template.getIcon(), template.getName(),
	// template.getQuality(), ((GameItemGainEntry) gainEntry).getCount(),
	// item.getInstanceId(), template.getId());
	// if (item instanceof ItemEx) {
	// award.setDesc(template.getDesc());// 物品描述
	// } else if (item instanceof EquipmentEx) {
	// EquipmentEx equip = (EquipmentEx) item;
	// award.setDesc("装备战力"
	// + equip.getEquCombatValue());// 装备评分
	// }
	// }
	// }
	// } else if (gainEntry instanceof ShiMoSPGainEntryRU) {
	// ShiMoSPGainEntryRU shimo = (ShiMoSPGainEntryRU) gainEntry;
	// ShiMoService shimoService = ServiceContainer.getDefault()
	// .get(ShiMoService.class);
	// SMTemplate smTemplate = shimoService.smtemplates
	// .get(shimo.smTempleteId);
	// if (smTemplate != null) {
	// award = new InstanceAwardInfoObj(
	// DropItemEx.DROP_TYPE_SHIMO_SP,
	// smTemplate.initHeadiconIndex, smTemplate.title,
	// smTemplate.starLeve, shimo.num, -1, -1);
	// }else{
	// log.error("[INITAWARDINFO]SHIMOID["+shimo.smTempleteId+"]");
	// }
	// }
	// return award;
	// }

	/**
	 * 将奖励信息放入packet
	 * 
	 * @param packet
	 * @param awardList
	 */
	// public static void putInstanceAwardInfo(Packet packet,
	// List<InstanceAwardInfoObj> awardList) {
	// packet.putInt(awardList.size());
	// for (InstanceAwardInfoObj awardinfo : awardList) {
	// packet.putInt(awardinfo.dropType);
	// packet.putInt(awardinfo.icon);
	// packet.putString(awardinfo.name);
	// packet.putInt(awardinfo.quality);
	// packet.putInt(awardinfo.count);
	// packet.putInt(awardinfo.itemId);
	// packet.putInt(awardinfo.instatnceId);
	// packet.putString(awardinfo.getDesc());
	// packet.putInt(awardinfo.getLevel());
	// }
	// }

	/**
	 * 2个日期间隔的天数
	 * 
	 * @param oldDay
	 * @param newDay
	 * @return
	 */
	public static int calDateSpace(Date oldDay, Date newDay) {
		Calendar calold = Calendar.getInstance();
		Calendar calnew = Calendar.getInstance();
		calold.setTime(oldDay);
		calnew.setTime(newDay);
		// 设置时间为0时
		calold.set(Calendar.HOUR_OF_DAY, 0);
		calold.set(Calendar.MINUTE, 0);
		calold.set(Calendar.SECOND, 0);
		calnew.set(Calendar.HOUR_OF_DAY, 0);
		calnew.set(Calendar.MINUTE, 0);
		calnew.set(Calendar.SECOND, 0);
		// 得到两个日期相差的天数
		int days = ((int) (calnew.getTime().getTime() / 1000) - (int) (calold.getTime().getTime() / 1000)) / 3600 / 24;
		return days;
	}

	/**
	 * 比较2个日期是否是同一天，同一天返回false
	 * 
	 * @param oldDay
	 * @param newDay
	 * @return
	 */
	public static boolean isAnotherDay(Date oldDay, Date newDay) {
		Calendar c1 = Calendar.getInstance();
		Calendar c2 = Calendar.getInstance();
		c1.setTime(oldDay);
		c2.setTime(newDay);
		if (c1.get(Calendar.YEAR) == c2.get(Calendar.YEAR) && c1.get(Calendar.MONTH) == c2.get(Calendar.MONTH)
				&& c1.get(Calendar.DAY_OF_MONTH) == c2.get(Calendar.DAY_OF_MONTH)) {
			return false;
		}
		return true;
	}

	public static final SimpleDateFormat SDF = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

	/**
	 * 根据提供的时间,和间隔计算距离当前时间最近的下次时间
	 * 
	 * @param firstDate
	 *            指定第一次时间
	 * @param period
	 *            时间间隔
	 * @return 当前时间之后的下次启动时间
	 * @throws ParseException
	 */
	public static Date calDate(String firstDate, int period) throws ParseException {
		Date date = new Date();
		Date nextEndDate = SDF.parse(firstDate);
		while (nextEndDate.before(date)) {
			long time = nextEndDate.getTime() + period;
			nextEndDate.setTime(time);
		}
		return nextEndDate;
	}

	/**
	 * 向某一地图中刷新npc
	 * 
	 * @param npcId
	 * @param mapId
	 * @param x
	 * @param y
	 */
	// public static void addUnit(int npcId, int mapId, int x, int y, BaseAIEx ai) {
	// ProjectData project =
	// ServiceContainer.getDefault().get(DataService.class).getData();
	// GameMapObject gmo = GameMapObject.findByID(project, npcId);
	// VMap map = null;
	// map = ((NormalVMapManager)
	// Platform.getWorld().getVMapManager(mapId)).getFirstVMap(mapId);
	// if (gmo == null)
	// return;
	// GameMapNPC npc = (GameMapNPC) gmo;
	// npc.refreshInterval = -1;
	// npc.visible = true;
	// npc.dynamicRefresh = false;
	// Object o = map.getVMapManager().createUnit(gmo, map);
	//
	// if (o instanceof Unit) {
	// Unit u = (Unit) o;
	// if(ai != null && o instanceof Creature){
	// ((Creature)u).setAi(ai);
	// }
	// ObjectAccessor.addGameObject(u);
	// u.addToMap(map, x, y);
	// }
	// }

	/**
	 * 向玩家所在副本中刷新npc
	 * 
	 * @param npcId
	 * @param mapId
	 * @param x
	 * @param y
	 */
	// public static void addUnit(NormalInstance instance, int npcId, int mapId, int
	// x, int y, BaseAIEx ai) {
	// if(instance == null)
	// return;
	// ProjectData project =
	// ServiceContainer.getDefault().get(DataService.class).getData();
	// GameMapObject gmo = GameMapObject.findByID(project, npcId);
	// VMap map = instance.getMap(mapId);
	// if (gmo == null)
	// return;
	// GameMapNPC npc = (GameMapNPC) gmo;
	// npc.refreshInterval = -1;
	// npc.visible = true;
	// npc.dynamicRefresh = false;
	// Object o = map.getVMapManager().createUnit(gmo, map);
	//
	// if (o instanceof Unit) {
	// Unit u = (Unit) o;
	// if(ai != null && o instanceof Creature){
	// ((Creature)u).setAi(ai);
	// }
	// ObjectAccessor.addGameObject(u);
	// u.addToMap(map, x, y);
	// }
	// }

	/**
	 * 大功能项开启的最小任务id
	 * 背包--任务--武器--装备--使魔--占星--公会↑-签到--活动--赏金猎人↑--小助手↑--交易所↑--我要--活跃度--装备强化--世界地图--赏金任务--悬赏副本
	 */
	public static final int[] FUN_OPEN_QUESTIDS = new int[] { 0, 0, 27, 195, 37, 43, 0, 30, /* 活动 */14, 0, 0, 0, 44, 82,
			205, 17, 97/* 赏金任务 */, 31, 98/* 猎衔 */ };

	/**
	 * 各个功能开启的任务id，策划给定
	 */
	public static final int WEAPON_ARSENAL_OPEN_QUESTID = 27;// 武器库
	public static final int WEAPON_UPLEVEL_OPEN_QUESTID = 27;// 武器升级
	public static final int WEAPON_BLESSING_OPEN_QUESTID = 27;// 武器祝福

	public static final int EQUIP_INTENSIFY_OPEN_QUESTID = 205;// 装备强化
	public static final int EQUIP_RUNEUP_OPEN_QUESTID = 74;// 装备符文升级
	public static final int EQUIP_ENCHANTING_OPEN_QUESTID = 102;// 装备附魔

	public static final int SHIMO_GUAN_OPEN_QUESTID = 37;// 使魔馆
	public static final int SHIMO_ZHEN_OPEN_QUESTID = 18;// 使魔阵
	public static final int SHIMO_SHOP_OPEN_QUESTID = 66;// 使魔商店
	public static final int SHIMO_FRIENDS_OPEN_QUESTID = 18;// 使魔小伙伴

	public static final int ZHANXING_OPEN_QUESTID = 43;// 占星
	public static final int BOUNTY_QUEST_OPEN_QUESTID = 97;// 赏金任务
	public static final int BOUNTY_INSTANCE_OPEN_QUESTID = 31;// 悬赏副本

	/**
	 * 通知客户端怪物血量变化
	 * 
	 * @param attributeIndex
	 * @param attributeValue
	 * @param flyStringIndex
	 *            飘字索引
	 * @author kunkun.zhu
	 */
	// public static void notifyAttributeChange(BaseUnit unit,int attributeIndex,int
	// attributeValue,String flyString){
	// Packet pt = new Packet(OpCodeEx.SPRITE_NOTIFY_ATTRIBUTE_SERVER);
	// pt.putInt(unit.getInstanceId());
	// pt.putUTF(flyString);
	// pt.put(attributeIndex);
	// pt.putInt(attributeValue);
	// unit.broadcast(pt, true);
	// }

	/**
	 * 通过邮件发放掉落奖励(只限获得奖励，gain()方法获得失败，背包已满的情况调用)
	 * 
	 * @param gain
	 *            掉落
	 * @param cause
	 *            事务
	 * @param mailTitle
	 *            邮件标题
	 * @param mailContent
	 *            邮件内容，如果是null，则为默认内容
	 * @return 操作是否成功
	 */
	// public static boolean gainByMail(Gain gain,String cause,String mailTitle,
	// String mailContent) {
	// List<GainEntry> entrys = gain.getGainEntrys();
	// List<MailAttachment> attachList = new ArrayList<MailAttachment>();
	// StringBuilder sBuilder = new StringBuilder("获得");
	// for (GainEntry entry : entrys) {
	// if (entry instanceof GameItemGainEntry) {
	// //物品
	// GameItemGainEntry gameGain = (GameItemGainEntry) entry;
	// ItemMailAttachmentEx itemAttach = new ItemMailAttachmentEx(
	// gameGain.getItem(), gameGain.getCount());
	// attachList.add(itemAttach);
	// if (sBuilder.length() > 2) {
	// sBuilder.append("、");
	// }
	// sBuilder.append(gameGain.getItem().getTemplate().getName())
	// .append(gameGain.getCount()).append("ge");
	// } else if (entry instanceof ShiMoSPGainEntryRU) {
	// //使魔碎片
	// ShiMoSPGainEntryRU shimoGain = (ShiMoSPGainEntryRU) entry;
	// ShimoSPMailAttachment attach = new ShimoSPMailAttachment(
	// shimoGain.smTempleteId, shimoGain.num);
	// attachList.add(attach);
	// if (sBuilder.length() > 2) {
	// sBuilder.append("、");
	// }
	// sBuilder.append("使魔碎片");
	// } else if (entry instanceof TreasureGainEntryRU) {
	// //藏宝图
	// TreasureGainEntryRU treasureGain = (TreasureGainEntryRU) entry;
	// TreasureMailAttachment attach = new TreasureMailAttachment(
	// treasureGain.value);
	// attachList.add(attach);
	// if (sBuilder.length() > 2) {
	// sBuilder.append("、");
	// }
	// sBuilder.append("藏宝图碎片");
	// } else if (entry instanceof MoneyGainEntryRU) {
	// //金币
	// MoneyGainEntryRU moneyGain = (MoneyGainEntryRU) entry;
	// MoneyMailAttachment attach = new MoneyMailAttachment(moneyGain.value);
	// attachList.add(attach);
	// if (sBuilder.length() > 2) {
	// sBuilder.append("、");
	// }
	// sBuilder.append("金币");
	// } else if (entry instanceof BoundMoneyGainEntryRU) {
	// //蓝钻
	// BoundMoneyGainEntryRU moneyGain = (BoundMoneyGainEntryRU) entry;
	// AwardMoneyMailAttachment attach = new
	// AwardMoneyMailAttachment(moneyGain.value);
	// attachList.add(attach);
	// if (sBuilder.length() > 2) {
	// sBuilder.append("、");
	// }
	// sBuilder.append("蓝钻");
	// } else if (entry instanceof FuWenTokenGainEntryRU){
	// FuWenTokenGainEntryRU fuwen = (FuWenTokenGainEntryRU) entry;
	// FuWenTokenMailAttachment attach = new FuWenTokenMailAttachment(fuwen.value);
	// attachList.add(attach);
	// if (sBuilder.length() > 2) {
	// sBuilder.append("、");
	// }
	// sBuilder.append("符文币");
	// }else{
	// return false;
	// }
	// }
	// sBuilder.append("，请收取附件");
	// if (null == mailContent) {
	// mailContent = sBuilder.toString();
	// }
	// MailServiceImpl mailServiceImpl = ServiceContainer.getDefault().get(
	// MailServiceImpl.class);
	// if (null == mailServiceImpl)
	// return false;
	// MailAttachment[] attachs = new MailAttachment[attachList.size()];
	// mailServiceImpl.sendSystemMail(Message.SYSTEM_NAME,
	// gain.getPlayer().getInstanceId(), mailTitle, mailContent,
	// attachList.toArray(attachs), 0, cause);
	// return true;
	// }
	/**
	 * 精灵是否处于无敌状态
	 * 
	 * @author kunkun.zhu
	 */
	// public static boolean unitIsInvincible(CombatUnit unit){
	// boolean ret = false;
	// if(unit instanceof PlayerEx){
	// PlayerEx playerEx = (PlayerEx)unit;
	// ret = playerEx.isInvincible();
	// }else if(unit instanceof CreatureEx){
	// CreatureEx creatureEx = (CreatureEx)unit;
	// ret = creatureEx.isInvincible();
	// }
	// return ret;
	// }

	/**
	 * 下发武器信息 template - 不可以为null creature - 可以为null
	 * 
	 * @author kunkun.zhu
	 */
	// public static void sendEquInfo(Packet pt ,NPCTemplateEx template,CreatureEx
	// creature){
	// //怪物从NPCTemplate中读取装备信息
	// HashMap<Integer, String> tagMap1 = new HashMap<Integer, String>();
	// int currentWeaponIndex = template.mainWeaponIndex;
	// boolean isSendAllEqu = template.sendAllEqu;
	// if(creature != null){
	// template = (NPCTemplateEx)creature.getTemplate();
	// currentWeaponIndex = creature.currentWeaponIndex;
	// isSendAllEqu = creature.isSendAllEqu();
	// }
	// if(creature != null && creature.transFormTemplateId != -1){
	// DataService ds = ServiceContainer.getDefault().get(DataService.class);
	// template = (NPCTemplateEx) ds.getData().findObject(NPCTemplate.class,
	// creature.transFormTemplateId);
	// }
	//
	// tagMap1.putAll(template.tagMap);
	// tagMap1.remove(currentWeaponIndex);
	// if(template.tagMap.get(currentWeaponIndex) != null){
	// String tagString = template.tagMap.get(currentWeaponIndex);
	// pt.putUTF(tagString);
	// pt.put(getWeaponTypeByTag(tagString));
	// }else{
	// pt.putUTF("");
	// pt.put((byte) -1);
	// }
	// //只有不在试炼场里的怪才下发其他装备
	// if(isSendAllEqu){
	// pt.put(tagMap1.size());
	// for(int key : tagMap1.keySet()){
	// String tagString = tagMap1.get(key);
	// pt.putUTF(tagString);
	// }
	// }else{
	// pt.put(0);
	// }
	//
	// }

	/**
	 * 根据人物模型上的挂接点名称来判断这个挂接点所挂接武器的类型 （大剑-0,双刀 -1，火枪-2，法杖 - 3,镰刀-4， 法典-5）
	 * 
	 * @param tagString
	 * @return
	 */
	public static int getWeaponTypeByTag(String tagString) {
		int ret = -1;
		if (tagString != null && tagString.length() > 0) {
			int firstIndex = tagString.indexOf(",");
			int lastIndex = tagString.lastIndexOf(",");
			String str = tagString.substring(firstIndex + 1, lastIndex);
			if (str.equals("dajian")) {// 大剑
				ret = 0;
			} else if (str.equals("shuangdao")) {// 双刀
				ret = 1;
			} else if (str.equals("huoqiang")) {// 火枪
				ret = 2;
			} else if (str.equals("fazhang")) {// 法杖
				ret = 3;
			} else if (str.equals("liandao")) {// 镰刀
				ret = 4;
			} else if (str.equals("book")) {// 法典
				ret = 5;
			}

		}
		return ret;
	}

	/**
	 * 把一个字符串分成用指定字符隔开的多个字符串.
	 * 
	 * @param s
	 *            原始字符串
	 * @param ch
	 *            分隔字符
	 * @return 分割后的数组
	 */
	public static String[] splitString(String s, char ch) {
		int startIndex = 0;
		int endIndex = 0;
		List<String> vs = new ArrayList<String>();
		while (true) {
			endIndex = s.indexOf(ch, startIndex);
			if (endIndex == -1) {
				vs.add(s.substring(startIndex));
				break;
			} else {
				vs.add(s.substring(startIndex, endIndex));
				startIndex = endIndex + 1;
			}
		}
		String[] strs = new String[vs.size()];
		vs.toArray(strs);
		return strs;
	}

	/**
	 * 把格式为n,n,n的字符串解析为int数组。
	 * 
	 * @param str
	 * @param delimiter
	 * @return
	 */
	public static int[] stringToIntArray(String str, char delimiter) {
		if (str == null || str.length() == 0) {
			return new int[0];
		}
		String[] tmp = splitString(str, delimiter);
		int[] ret = new int[tmp.length];
		for (int i = 0; i < ret.length; i++) {
			ret[i] = Integer.parseInt(tmp[i]);
		}
		return ret;
	}
	
	public static String conver2UTF8(String str) throws Exception {
		String encoding = "";
		byte[] buf = str.getBytes();

		// 根据前缀自动判断编码，如果没有指定则采用缺省GBK
		// unicode litte-endian: FF FE
		// unicode big-endian: FE FF
		// utf8: EF BB BF
		int skip = 0;
		if (buf.length >= 3 && buf[0] == (byte) 0xEF && buf[1] == (byte) 0xBB && buf[2] == (byte) 0xBF) {
			encoding = "UTF-8";
			skip = 3;
		} else if (buf.length >= 2 && buf[0] == (byte) 0xFE && buf[1] == (byte) 0xFF) {
			encoding = "UTF-16BE";
			skip = 2;
		} else if (buf.length >= 2 && buf[0] == (byte) 0xFF && buf[1] == (byte) 0xFE) {
			encoding = "UTF-16LE";
			skip = 2;
		} else {
			encoding = "GBK";
		}
		return new String(buf, skip, buf.length - skip, encoding);
	}
	
	public static String getFileEncode(File file) throws Exception {
		String encoding = "";
		FileInputStream fis = null;
		try {
			byte[] buf = new byte[3];
			fis = new FileInputStream(file);
			new DataInputStream(fis).readFully(buf);

			// 根据前缀自动判断编码，如果没有指定则采用缺省GBK
			// unicode litte-endian: FF FE
			// unicode big-endian: FE FF
			// utf8: EF BB BF
			if (buf.length >= 3 && buf[0] == (byte) 0xEF && buf[1] == (byte) 0xBB && buf[2] == (byte) 0xBF) {
				encoding = "UTF-8";
			} else if (buf.length >= 2 && buf[0] == (byte) 0xFE && buf[1] == (byte) 0xFF) {
				encoding = "UTF-16BE";
			} else if (buf.length >= 2 && buf[0] == (byte) 0xFF && buf[1] == (byte) 0xFE) {
				encoding = "UTF-16LE";
			} else {
				encoding = "GBK";
			}
			
		} catch (Exception e) {
			throw e;
		} finally {
			if (fis != null) {
				try {
					fis.close();
				} catch (IOException e) {
				}
			}
		}
		return encoding;
	}
	/**
	 * 获取文本文件
	 */
	public static String loadText(File file, String encoding) throws Exception {
		FileInputStream fis = null;
		try {
			byte[] buf = new byte[(int) file.length()];
			fis = new FileInputStream(file);
			new DataInputStream(fis).readFully(buf);

			// 根据前缀自动判断编码，如果没有指定则采用缺省GBK
			// unicode litte-endian: FF FE
			// unicode big-endian: FE FF
			// utf8: EF BB BF
			// other: none
			// String encoding;
			int skip = 0;
			if (buf.length >= 3 && buf[0] == (byte) 0xEF && buf[1] == (byte) 0xBB && buf[2] == (byte) 0xBF) {
				encoding = "UTF-8";
				skip = 3;
			} else if (buf.length >= 2 && buf[0] == (byte) 0xFE && buf[1] == (byte) 0xFF) {
				encoding = "UTF-16BE";
				skip = 2;
			} else if (buf.length >= 2 && buf[0] == (byte) 0xFF && buf[1] == (byte) 0xFE) {
				encoding = "UTF-16LE";
				skip = 2;
			} else {
				encoding = "GBK";
			}

			return new String(buf, skip, buf.length - skip, encoding);
		} catch (IOException e) {
			throw e;
		} finally {
			if (fis != null) {
				try {
					fis.close();
				} catch (IOException e) {
				}
			}
		}

	}

	/**
	 * 猎人升级经验
	 */
	public static int[] hunterUpLeveExp = new int[] { 10, 20, 30, 40, 100, 120, 140, 160, 270, 300, /* 1~10 */660, 720,
			975, 1050, 1350, 1920, 2805, 3510, 3990, 4200, /* 11~20 */
			4725, 4950, 5520, 5760, 6375, 6630, 7290, 7560, 8265, 9450, /* 21~30 */10230, 11520, 12375, 13770, 14700,
			16200, 17205, 18810, 19890, 21600, /* 31~40 */22755, 24570, 25800, 27720, 29025, 31050, 32430, 34560, 36015,
			38250, /* 41~50 */42075, 47580, 54855, 62370, 68475, 73080, 76095, 78300, 81420, 83700, /* 51~60 */86925,
			89280, 92610, 95040, 98475, 100980, 104520, 107100, 110745, 112350,/* 61~70 */
	};

	/**
	 * 当前等级升级所需经验
	 */
	public static int getExpByLevel(int level) {
		if (level > 0) {
			return hunterUpLeveExp[level];
		} else {
			return 112350;
		}
	}

	/**
	 * 把格式为n,n,n的字符串解析为byte数组。
	 * 
	 * @param str
	 * @param delimiter
	 * @return
	 */
	public static byte[] stringToByteArray(String str, char delimiter) {
		if (str == null || str.length() == 0) {
			return new byte[0];
		}
		String[] tmp = splitString(str, delimiter);
		byte[] ret = new byte[tmp.length];
		for (int i = 0; i < ret.length; i++) {
			ret[i] = Byte.parseByte(tmp[i]);
		}
		return ret;
	}

	/**
	 * 把byte数组转换为格式为n,n,n的字符串。
	 * 
	 * @param arr
	 * @param delimiter
	 * @return
	 */
	public static String byteArrayToString(byte[] arr, char delimiter) {
		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < arr.length; i++) {
			if (i > 0) {
				sb.append(delimiter);
			}
			sb.append(arr[i]);
		}
		return sb.toString();
	}

	/**
	 * 保存字符串到文件，采用GBK编码。
	 */
	public static void saveFileContent(File dest, String content) throws IOException {
		saveFileContent(dest, content, "GBK");
	}

	public static void saveFileContent(File dest, String content, String encoding) throws IOException {
		FileOutputStream fos = null;
		try {
			fos = new FileOutputStream(dest);
			// 处理BOM
			if ("UTF-8BOM".equals(encoding)) {
				fos.write(0xEF);
				fos.write(0xBB);
				fos.write(0xBF);
				encoding = "UTF-8";
			} else if ("UTF-16LEBOM".equals(encoding)) {
				fos.write(0xFF);
				fos.write(0xFE);
				encoding = "UTF-16LE";
			} else if ("UTF-16BEBOM".equals(encoding)) {
				fos.write(0xFE);
				fos.write(0xFF);
				encoding = "UTF-16BE";
			}
			fos.write(content.getBytes(encoding));
		} catch (IOException e) {
			throw e;
		} finally {
			if (fos != null) {
				try {
					fos.close();
				} catch (IOException e) {
				}
			}
		}
	}

	/**

	/**
	 * 判断一个点是否在矩形范围内
	 * 
	 * @param point
	 * @param leftTopPoint
	 * @param rightBottomPoint
	 * @return
	 */
	public static boolean isInRect(Vector2f point, Vector2f leftTopPoint, Vector2f rightBottomPoint) {
		return point.x > leftTopPoint.x && point.x < rightBottomPoint.x && point.y > leftTopPoint.y
				&& point.y < rightBottomPoint.y;
	}

}
